// 螺旋矩阵2

package Leetcode;

class solution_059 {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int currentX = 0;
        int currentY = -1;
        int direction = 0; // 0,1,2,3表示右，下，左，上
        for (int i = 1; i <= n * n; i++) {
            // 朝右
            if (direction == 0) {
                if (currentY + 1 < n && result[currentX][currentY + 1] == 0) {
                    currentY++;
                }
                // 超过右边界或者右边已经被赋值
                else {
                    direction = 1;
                    currentX++;
                }
                result[currentX][currentY] = i;
                continue;
            }
            // 朝下
            if (direction == 1) {
                if (currentX + 1 < n && result[currentX + 1][currentY] == 0) {
                    currentX++;
                }
                // 超过下边界或者下边已经被赋值
                else {
                    direction = 2;
                    currentY--;
                }
                result[currentX][currentY] = i;
                continue;
            }
            // 朝左
            if (direction == 2) {
                if (currentY - 1 >= 0 && result[currentX][currentY - 1] == 0) {
                    currentY--;
                }
                // 超过左边界或者左边已经被赋值
                else {
                    direction = 3;
                    currentX--;
                }
                result[currentX][currentY] = i;
                continue;
            }
            // 朝上
            if (direction == 3) {
                if (currentX - 1 >= 0 && result[currentX - 1][currentY] == 0) {
                    currentX--;
                }
                // 超过上边界或者上边已经被赋值
                else {
                    direction = 0;
                    currentY++;
                }
                result[currentX][currentY] = i;
                continue;
            }
        }
        return result;
    }
}

public class Solution059 {

}
